package com.mmall.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.dao.*;
import com.mmall.pojo.*;
import com.mmall.service.AddressService;
import com.mmall.service.GoodsService;
import com.mmall.util.DateUtils;
import com.mmall.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("GoodsService")
@Transactional
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private JedisClient jedisClient;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Override
    public ServerResponse insertGoods(Goods goods) {
        goods.setSellStatus(Const.SELL_STATUS_YES);//默认开启售卖状态
        if(goodsMapper.insertSelective(goods)>0){
//            List<Goods> goodsList = goodsMapper.selectAll();
//            if(goodsList != null && goodsList.size()>0){
//                for (Goods g: goodsList) {
//                    g.setPictureArray(JSONArray.parseArray(g.getPicture()));
//                    g.setCreateTimeText(DateUtils.formatDateTime(g.getCreateTime()));
//                }
//                jedisClient.set(Const.PREFIX_REDIS_GOODS_LIST,JsonUtils.objectToJson(goodsList));
//            }
            return ServerResponse.cerateBySuccessMessage("商品发布成功");
        }
        return ServerResponse.createByErrorMessage("商品发布失败");
    }

    @Override
    public ServerResponse selectGoods(Integer id,Integer userId) {
            Goods goods = goodsMapper.selectByPrimaryKey(id);
            if(goods != null){
                goods.setPictureArray(JSONArray.parseArray(goods.getPicture()));
                goods.setCreateTimeText(DateUtils.formatDateTime(goods.getCreateTime()));
                if(goodsMapper.selectCollection(userId,goods.getId())>0){//判断是否收藏该商品
                    goods.setIsCollection(0);//yes
                }else {
                    goods.setIsCollection(1);//no
                }

                if(goods.getUserId()==userId){
                    goods.setIsShowBuyBtn(1);
                }else {
                    goods.setIsShowBuyBtn(0);
                }
                List<Message> messageList = messageMapper.selectListByGoodsId(goods.getId());
                if(messageList!=null && messageList.size()>0){
                    for (Message message:messageList) {
                        message.setCreateTimeText(DateUtils.formatDateTime(message.getCreateTime()));
                    }
                }
                goods.setMessageList(messageList);

                Order order = orderMapper.selectByUserIdGoodsId(userId,goods.getId());
                if(order!=null){
                    goods.setOrderId(order.getId());//该用户已对此商品生成订单
                }else {
                    goods.setOrderId(null);//未生成订单
                }
                return ServerResponse.cerateBySuccess("查询成功",goods);
            }
            return ServerResponse.createByErrorMessage("查无信息");
    }

    @Override
    public ServerResponse updateGoods(Goods goods) {
        if(goodsMapper.updateByPrimaryKeySelective(goods)>0){
            return ServerResponse.cerateBySuccessMessage("商品信息更新成功");
        }
        return ServerResponse.createByErrorMessage("商品信息更新失败");
    }

    @Override
    public ServerResponse deleteGoods(Integer id) {
        if(goodsMapper.deleteByPrimaryKey(id)>0){
            return ServerResponse.cerateBySuccessMessage("商品删除成功");
        }
        return ServerResponse.createByErrorMessage("商品删除失败");
    }

    public ServerResponse findGoodsListByUserId(Integer userId){
        List<Goods> goodsList = goodsMapper.selectGoodsListByUserId(userId);
        if(goodsList !=null && goodsList.size()>0){
            for (Goods goods:goodsList) {
                goods.setCreateTimeText(DateUtils.formatDateTime(goods.getCreateTime()));
                goods.setPictureArray(JSONArray.parseArray(goods.getPicture()));
            }
            return ServerResponse.cerateBySuccess("查询成功",goodsList);
        }
        return ServerResponse.createByErrorMessage("无商品列表");
    }

    public ServerResponse findAll(){
//        try {
//           String goodListString = jedisClient.get(Const.PREFIX_REDIS_GOODS_LIST);
//           if(goodListString==null){
               List<Goods> goodsList = goodsMapper.selectAll();
               if(goodsList!=null && goodsList.size()>0){
                   for (Goods goods: goodsList){
                       goods.setPictureArray(JSONArray.parseArray(goods.getPicture()));
                       goods.setCreateTimeText(DateUtils.formatDateTime(goods.getCreateTime()));
                   }
               }
//               String cacheString = JsonUtils.objectToJson(goodsList);
//               jedisClient.set(Const.PREFIX_REDIS_GOODS_LIST, cacheString);
               return ServerResponse.cerateBySuccess("查询成功",goodsList);
//           }
//            return ServerResponse.cerateBySuccess("查询成功",JsonUtils.jsonToList(goodListString,Goods.class));
//        }catch (Exception e){
//            e.printStackTrace();
//            return ServerResponse.createByErrorMessage("查询出错");
//        }
    }

   public ServerResponse findGoodsWithDefaultAdress(Integer id,Integer userId){
        Goods goods = goodsMapper.selectByPrimaryKey(id);
       goods.setPictureArray(JSONArray.parseArray(goods.getPicture()));
        if(goods==null){
            return ServerResponse.createByErrorMessage("无信息");
        }

        Address address = addressMapper.selectDefaultAdress(userId);
       String goodsString = JsonUtils.objectToJson(goods);
       JSONObject jsonObject = JSONObject.parseObject(goodsString);
        if(address!=null){
            jsonObject.put("address",address.getProvince()+address.getCity()+address.getDetailedAddress());
            jsonObject.put("receivePerson",address.getReceivePerson());
            jsonObject.put("receivePhone",address.getReceivePhone());
        }else {
            jsonObject.put("address",null);
            jsonObject.put("receivePerson",null);
            jsonObject.put("receivePhone",null);
        }
        return ServerResponse.cerateBySuccess("查询成功",jsonObject);


   }


   public ServerResponse collectionGoods(Integer userId,Integer goodsId){
        if(goodsMapper.collectionGoods(userId,goodsId)>0){
            return ServerResponse.cerateBySuccessMessage("收藏成功");
        }
        return ServerResponse.createByErrorMessage("收藏失败");
   }

    public ServerResponse cancelCollectionGoods(Integer userId,Integer goodsId){
        if(goodsMapper.cancelCollectionGoods(userId,goodsId)>0){
            return ServerResponse.cerateBySuccessMessage("已取消收藏");
        }
        return ServerResponse.createByErrorMessage("取消收藏出错");
    }

    public ServerResponse selectListByGoodsType(String goodsType){
        List<Goods> goodsList = goodsMapper.selectListByGoodsType(goodsType);
        if(goodsList!=null && goodsList.size()>0){
            for (Goods goods: goodsList){
                goods.setPictureArray(JSONArray.parseArray(goods.getPicture()));
                goods.setCreateTimeText(DateUtils.formatDateTime(goods.getCreateTime()));
            }
        }
        return ServerResponse.cerateBySuccess("查询成功",goodsList);
    }

    public ServerResponse findListByEntity(Goods goods){
        List<Goods> goodsList = goodsMapper.selectListByEntity(goods);
        if(goodsList !=null && goodsList.size()>0){
            for (Goods g:goodsList) {
                g.setCreateTimeText(DateUtils.formatDateTime(g.getCreateTime()));
                g.setPictureArray(JSONArray.parseArray(g.getPicture()));
                g.setPastMinutes(DateUtils.pastMinutes(g.getCreateTime()));
                g.setPastHour(DateUtils.pastHour(g.getCreateTime()));
            }
        }
        return ServerResponse.cerateBySuccess("获取列表成功",goodsList);
    }

    public ServerResponse findCollectionList(Integer userId){
        List<Goods> goodsList = goodsMapper.selectCollectionList(userId);
        if(goodsList != null && goodsList.size()>0){
            for (Goods goods:goodsList) {
                goods.setPictureArray(JSONArray.parseArray(goods.getPicture()));
                goods.setCreateTimeText(DateUtils.formatDateTime(goods.getCreateTime()));
            }
        }
        return ServerResponse.cerateBySuccess("查询成功",goodsList);
    }
}
